package com.andnnl.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;

/**
 * 每隔一秒都会取最新的资源文件
 */
public class ConfigFileHelper
{
	private static Logger logger = LoggerFactory.getLogger(ConfigFileHelper.class);
	private final static MyResourceBundleControl ctl = new MyResourceBundleControl();
	private ResourceBundle resourceBundle;

	public ConfigFileHelper(String propertyFileName )
	{
//		 resourceBundle = ResourceBundle.getBundle( propertyFileName );
        //取最新
		resourceBundle= ResourceBundle.getBundle(propertyFileName, Locale.getDefault(), ctl);

	}
	public Set<String> keySet(){
		return resourceBundle.keySet();
	}
	public Enumeration<String> getKeys(){
		return resourceBundle.getKeys();
	}
	public String getString(String key)
	{

		if (key == null || key.equals("") || key.equals("null"))
		{
			return "";
		}

		String result = "";

		try
		{
			result = resourceBundle.getString(key);
			if( result == null )
				result = "";
			
			result = result.trim();

		} catch (Exception e)
		{

			e.printStackTrace();

		}

		return result;

	}
	
	public int getInt(String key ,int defaultValue)
	{
		int i = 0;
		String str = getString( key );
		if( str.equals("") )
			i = defaultValue;
		try
		{
			i = Integer.parseInt( str );
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return i;
	}
	/**
	 * 重载控制器
	 */
	private static class MyResourceBundleControl extends ResourceBundle.Control {

		@Override
		public long getTimeToLive(String baseName, Locale locale) {
			return 1000;
		}

		@Override
		public boolean needsReload(String baseName, Locale locale,
								   String format, ClassLoader loader, ResourceBundle bundle,
								   long loadTime) {
			return true;
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		ConfigFileHelper c = new ConfigFileHelper("config");
//		logger.info(c.getString("redis_host"));
//		logger.info(c.getInt("redis_port",6379));
//
//		logger.info(c.getString("memcache_host"));
//		logger.info(c.getInt("memcache_port",11211));
	  
	}

}

